<?php
/**
 * Created by PhpStorm.
 * User: hda
 * Date: 2017/7/1
 * Time: 下午4:16
 */

namespace app\user\controller;

use icontroller\wechat\AController;
use library\common\str;
use library\tencent\wechat\wechat_index\PayManagement;
use model\Account as ac;
use model\AccountBill;
use model\AccountPayment;
use model\AccountRechargeOrder;
use model\AccountWechat;
use model\AccountWithdrawOrder;
use think\Db;
use think\Request;

class Account extends AController
{

    public function index()
    {
        $acc = new ac();
        $info = $acc->where(["id" => $this->account_id])->order('id', 'desc')->field("money")->find();
        $this->assign("info", $info);
        return view();
    }

    public function get_account(){
        if ($this->request->isAjax()){
            $info = ac::getField("money",["id"=>$this->account_id]);
            $this->success("获取成功",null,$info);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="获取钱帐列表">
    public function account_bill()
    {
        $type = input("type", 0);
        $page = input('page', 0);                      //分页
        $count = config('paginate.list_rows');         //每页数量
        $ap = new AccountPayment();
        $where = ["account_id" => $this->account_id];
        if (!empty($type)) {
            $where["pay_type"] = $type;
        }
        $list = $ap->where($where)->order('id', 'desc')->page($page, $count)->select();
        $this->success("获取成功", null, $list);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="充值">
    public function recharge()
    {
        $request = Request::instance();
        if ($request->isAjax()) {
            $money = input("money", 0);
            if ($money <= 0 || !is_numeric($money)) {
                $this->error("充值金额错误");
            }
            $aw = new AccountWechat();
            $wechat = $aw->where(['account_id' => $this->account_id])->find();
            $openid = $wechat->openid;
//      $openid="oy2HRv8Pak3uXD1ya-Q3V9wbEONw";
            $body = '用户充值';

            $total_fee = $money * 100;
            $spbill_create_ip = $this->request->ip();
            $pay_no = str::orderNo();
            $data0 = array(
                "account_id" => $this->account_id,
                "pay_no" => $pay_no,
                "pay_money" => $money,
                'remark' => '充值(支付中)',
                'pay_type' => 3,
            );

            $res0 = AccountPayment::create($data0);
            if (!$res0) {
                $this->error("系统出错，请稍后重试");
            }
            $data1 = array(
                "account_id" => $this->account_id,
                "order_sn" => $pay_no,
                "pay_amount" => $money,
                'payment_id' => $res0->id
            );

            $res1 = AccountRechargeOrder::create($data1);
            if (!$res1) {
                $this->error("系统出错，请稍后重试");
            }

            $pay = PayManagement::instance();
            $params = array(
                'openid' => $openid,
                'body' => $body,
                'out_trade_no' => $pay_no,
                'spbill_create_ip' => $spbill_create_ip,
                'total_fee' => $total_fee,
                'attach' => 4
            );

            $res = $pay->unifiedOrder($params);
            $jsApiParameters = $pay->getJsPayParameters($res['prepay_id']);
            $this->success("提交成功!", null, $jsApiParameters);

//        $order = $this->logic_recharge($param);
//        $this->assign('order', $order);
        }
        return view();
    }

    // </editor-fold>


    public function set_pwd()
    {
        return view();
    }

    public function set_pay_password_save()
    {
        $param = array(
            'password' => input('password'),
            'password_confirm' => input('password_confirm')
        );
        if (empty($param["password"])) {
            $this->error("支付密码不能设置为空");
        }
        if ($param['password'] != $param['password_confirm']) {
            $this->error("两次密码不一致");
        }
        $data = array(
            'pay_password' => md5($param['password'])
        );
        $res = ac::update($data, ['id' => $this->account_id]);
        $this->success("保存成功");
    }

    //充值
//    public function logic_recharge($param)
//    {
//        $aro = new AccountRechargeOrder();
//        $account = new ac();
//        $order = $aro->where(['id' => $param['order_id']])->find();
//        $money = $account->where(['id' => $this->account_id])->value('money');
//        if ($order) {
//            $order['balance'] = $money;
//        }
//        return $order;
//    }

    // <editor-fold defaultstate="collapsed" desc="提现">
    public function withdraw()
    {
        $info = ac::getField("money,frozen_money", ["id" => $this->account_id]);
        $this->assign("info", $info);
        return view();
    }

    // </editor-fold>


    public function withdraw_submit()
    {
        $params = array(
            'money' => input('money')
        );
        $acc = new ac();
        $item = $acc->field('money,frozen_money')->where(['id' => $this->account_id])->find();
        if ($item['money'] <= 0) {
            $this->error('请输入金额');
        }
        if ($item['money'] < $params['money']) {
            $this->error('提现金额过大');
        }
        $order_sn = str::orderNo();
        Db::startTrans();
        $insert_data = array(
            "order_sn" =>$order_sn,
            'account_id' => $this->account_id,
            'create_time' => time(),
            'apply_money' => $params['money'],
            'flag_status' => 0
        );
        $res1 = AccountWithdrawOrder::create($insert_data);
        if (!$res1) {
            Db::rollback();
            $this->error('数据出错，请稍后再试');
        }
        $update_data = array(
            'frozen_money' => $item['frozen_money'] + $params['money'],
            'money' => $item['money'] - $params['money']
        );
        $res2 = ac::update($update_data, ['id' => $this->account_id]);
        if (!$res2) {
            Db::rollback();
            $this->error('数据出错，请稍后再试');
        }

        $data = [
            "account_id" => $this->account_id,
            'pay_type' => 4,
            "pay_no" => $order_sn,
            "pay_money" => $params['money'],
            "remark" => "申请提现成功,等待审核",
            'flag_pay' => 0,
            'flag_lock' => 1
        ];

        $result = AccountPayment::create($data);
        if (!$result) {
            Db::rollback();
            $this->error('数据出错，请稍后再试');
        }
        Db::commit();
        $this->success("申请提现成功，等待后台审核");
    }
}